package com.codecash.controller;

import com.codecash.controller.response.Result;
import com.codecash.entity.FeedBack;
import com.codecash.entity.User;
import com.codecash.service.UserService;
import com.codecash.util.JwtUtil;
import com.codecash.util.Md5Util;
import com.codecash.util.ThreadLocalUtil;
import jakarta.validation.constraints.Email;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password, @NotEmpty(message = "邮箱不能为空")
    @Email(message = "邮箱格式不正确") String email) {
        //查询用户
        // 查询用户名是否已存在
        User userByName = userService.findByUserName(username);
        if (userByName != null) {
            // 用户名被占用
            return Result.error("用户名已存在！");

        }
        // 查询邮箱是否已存在
        User userByEmail = userService.findByEmail(email);
        if (userByEmail != null) {
            // 邮箱已被占用
            return Result.error("该邮箱已被注册！");
        }
        // 注册新用户
        userService.register(username, password, email);
        return Result.success();
    }


    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        User loginUser = userService.findByUserName(username);
        if (loginUser == null) {
            return Result.error("用户不存在");

        }

        if (Md5Util.getMD5String(password).equals(loginUser.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", loginUser.getId());
            claims.put("username", loginUser.getUsername());
            String newToken = JwtUtil.genToken(claims);

            // 确保存储和验证时使用相同的键格式，并删除旧 token
            String tokenKey = "user_token:" + loginUser.getId();
            stringRedisTemplate.delete(tokenKey); // 删除旧 token

            // 存储新 token 到 Redis，1 小时有效期
            stringRedisTemplate.opsForValue().set(tokenKey, newToken, 1, TimeUnit.HOURS);
            return Result.success(newToken);
        }
        return Result.error("密码错误");
    }

    @GetMapping("/userInfo")
    public Result<User> userInfo(/*@RequestHeader(name = "Authorization")String token*/) {
        //根据用户名查询用户
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.findByUserName(username);
        return Result.success(user);

    }

    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user) {
        try {
            // 从 ThreadLocal 中获取当前用户的 ID
            Map<String, Object> map = (Map<String, Object>) ThreadLocalUtil.get();
            Integer currentUserId = (Integer) map.get("id");

            if (currentUserId == null) {
                return Result.error("无法获取用户信息，请重新登录");
            }

            // 确保用户只能更新自己的信息
            if (!currentUserId.equals(user.getId())) {
                return Result.error("您无权修改他人信息");
            }

            // 调用更新方法，仅更新当前用户的信息
            userService.updatePartial(currentUserId, user.getUsername(), user.getEmail());
            return Result.success("更新成功");
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }


    @PatchMapping("updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String, String> params, @RequestHeader("Authorization") String token) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要的参数");
        }

        // 从 ThreadLocal 获取用户信息
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null || map.get("username") == null) {
            return Result.error("用户未登录或身份验证失败");
        }
        String username = (String) map.get("username");
        User loginUser = userService.findByUserName(username);

        if (!loginUser.getPassword().equals(Md5Util.getMD5String(oldPwd))) {
            return Result.error("原密码填写不正确");
        }

        if (!newPwd.equals(rePwd)) {
            return Result.error("两次输入密码不一致");
        }

        // 更新密码
        userService.updatePwd(newPwd);

        // 删除 Redis 中的 token 以使旧 token 失效
        String tokenKey = "user_token:" + loginUser.getId();
        stringRedisTemplate.delete(tokenKey);

        return Result.success("密码更新成功，请重新登录");
    }
    //用户反馈
    @PostMapping("/call")
    public Result addCall(@RequestBody FeedBack feedBack) {
        userService.addCall(feedBack);
        return Result.success();
    }

}
